package com.jhf.youke.core.annotation;



import cn.hutool.json.JSONUtil;
import com.jhf.youke.core.exception.CheckKeyExceptionBase;
import com.jhf.youke.core.utils.CacheUtils;
import com.jhf.youke.core.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 *  针对ReadOnlyConnection注解进行切面编程
 *  @author RHJ
 *
 * **/
@Aspect
@Component
public class CheckKeyInterceptor implements Ordered {

	public static final Logger LOGGER = LoggerFactory.getLogger(CheckKeyInterceptor.class);
	public static final String REPETITION  = "1";

	@Around("@annotation(com.jhf.youke.core.annotation.CheckKey)")
	public Object proceed(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		LOGGER.info("check key");
		Object[] args = proceedingJoinPoint.getArgs();
		String json = JSONUtil.toJsonStr(args[0]);
		Map<String, Object> map = JSONUtil.toBean(json, Map.class);
		if(map != null) {
			checkKey(map);
		}
		//原有方法执行完毕
		Object result = proceedingJoinPoint.proceed();
		if(map != null) {
			saveKey(map);
		}
		return result;
	}

	@Override
	public int getOrder() {
		return 0;
	}

	public void checkKey(Map<String, Object> map) throws CheckKeyExceptionBase {
		String filter = parseMapForFilter(map);
		if(StringUtils.isNotBlank(filter)){
			String key = map.get(filter).toString();
			if(StringUtils.ifNull(key)){
				throw new CheckKeyExceptionBase("key不能为空!");
			}
			String check = CacheUtils.get(key);
			if (REPETITION.equals(check)) {
				throw new CheckKeyExceptionBase("重复提交!");
			}
		}else {
			throw new CheckKeyExceptionBase("key不能为空!");
		}
	}

	public void saveKey(Map<String, Object> map) throws Exception {
		String filter = parseMapForFilter(map);
		if(StringUtils.isNotBlank(filter)){
			String key = map.get(filter).toString();
			CacheUtils.set(key,"1", 20*60*60);
		}
	}


	public String parseMapForFilter(Map<String, Object> map ) {
		if (map == null) {
			return "";
		} else {
			for(String key : map.keySet()){
				if(key.contains("key")){
					return key;
				}
			}
		}
		return "";
	}


}